#!/usr/bin/env bash
function main() {
    for i in $@; do
        case $i in
            backup)
                backup
                ;;
            start)
                start
                ;;
            start)
                start
                ;;
            restart)
                restart
                ;;
            stop)
                stop $port
                ;;
            rollback)
                rollback
                ;;
            update)
                backup
                restart
                ;;
            ?)
                usage
                ;;

        esac
    done

    exit 0
}

function backup() {
    echo '备份'
    if [ ! -d "$backup_dir" ]; then
        mkdir -p $backup_dir
    fi

    cp $file $backup_dir$file.`date +"%Y%m%d%H%M"`
    return;
}

function restart() {
    echo '重启'
    stop
    start
    return;
}

function start() {
    echo '启动'
    nohup java -jar $file --spring.profiles.active=gray >/dev/null 2>err.log &
    return;
}

function stop(){
    echo '停止'
    netstat -anp|grep $1 |grep java|grep LISTEN|awk '{print $7}'|awk -F '/' '{print $1}'|xargs kill -9
    return;
}

function rollback(){
    echo '回滚'
    echo "回滚版本,先选择版本,按时间倒序排列"
    ls -lth $backup_dir/$file*
    read backup_file
    echo "回滚的文件是 ${backup_file}"
    echo "开始回滚"
    stop
    rm -f $file
    cp ${backup_file} $file
    start
    return;
}

function usage() {
   echo '
   console.sh stop
   console.sh start
   console.sh restart
   console.sh rollback
   console.sh backup
   '
}

# 判空,没有参数
if [ -z "$1" ]; then
    usage
    exit 1
fi

port=6060
backup_dir=/data/server/wefly/console/bak/
file=`ls -thr /data/server/wefly/console | grep  "wefly-console.*jar"  | head -1`
if [ ! -f $file ] ; then
    echo '文件不存在'
    exit 1
fi


main $@
